/**
 * 
 */
package pl.lodz.p.browarex.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import pl.lodz.p.browarex.dao.GenericDao;
import pl.lodz.p.browarex.model.Ingredient;
import pl.lodz.p.browarex.model.ProductOrder;

@Service
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class ProductOrderService implements GenericService<ProductOrder, Long> {

	@Autowired
	private GenericDao<ProductOrder, Long> productOrderDao;

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#upsert(java.lang.Object)
	 */
	@Override
	public void upsert(ProductOrder object) {
		List<ProductOrder> persistedObjects = findByGuid(object.getProductionID());
		if (persistedObjects.size() > 0) {
			ProductOrder po =persistedObjects.get(0);
			po.setAmount(object.getAmount());
			po.setDate(object.getDate());
			po.setProduct(object.getProduct());
			po.setProductId(object.getProductId());
			po.setProductionID(object.getProductionID());
			po.setRealization(object.isRealization());
			productOrderDao.update(po);
		}else {
		
			productOrderDao.create(object);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#delete(java.lang.Object)
	 */
	@Override
	public void delete(ProductOrder object) {
		List<ProductOrder> persistedObjects = findByGuid(object.getProductionID());
		for (ProductOrder po : persistedObjects) {
			productOrderDao.delete(po);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#find(java.io.Serializable)
	 */
	@Override
	public ProductOrder find(Long id) {
		return productOrderDao.findById(id);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#findByGuid(java.lang.String)
	 */
	@Override
	public List<ProductOrder> findByGuid(String guid) {
		return productOrderDao.findAllByProperty("productionID", guid);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see pl.net.beercrm.service.GenericService#list()
	 */
	@Override
	public List<ProductOrder> list() {
		return productOrderDao.findAll();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * pl.net.beercrm.service.GenericService#findByProperty(java.lang.String,
	 * java.lang.Object)
	 */
	@Override
	public List<ProductOrder> findByProperty(String property, Object value) {
		return productOrderDao.findAllByProperty(property, value);
	}

}
